{% extends "base.html" %}

{% block title %}设备数据 - {{ device.name }}{% endblock %}

{% block page_title %}设备数据 - {{ device.name }}{% endblock %}

{% block extra_css %}
<style>
.device-data {
    padding: 20px;
    background: white;
    border-radius: var(--border-radius);
    box-shadow: var(--box-shadow);
}

.data-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.data-filters {
    display: flex;
    gap: 20px;
    margin-bottom: 20px;
    padding: 15px;
    background: #f8f9fa;
    border-radius: 8px;
}

.data-chart {
    height: 100%;
    width: 100%;
}

.data-table {
    width: 100%;
    border-collapse: collapse;
}

.data-table th,
.data-table td {
    padding: 12px;
    text-align: left;
    border-bottom: 1px solid #eee;
}

.data-table th {
    background: #f8f9fa;
    font-weight: 600;
}

.data-table tr:hover {
    background: #f8f9fa;
}

.status-indicator {
    display: inline-block;
    width: 10px;
    height: 10px;
    border-radius: 50%;
    margin-right: 8px;
}

.status-online {
    background: #28a745;
}

.status-offline {
    background: #dc3545;
}

.device-info {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 20px;
    margin-bottom: 20px;
    padding: 15px;
    background: #f8f9fa;
    border-radius: 8px;
}

.info-item {
    display: flex;
    flex-direction: column;
}

.info-label {
    font-size: 0.9em;
    color: #666;
    margin-bottom: 5px;
}

.info-value {
    font-size: 1.1em;
    font-weight: 500;
}

.loading-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(255, 255, 255, 0.8);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000;
}

.loading-spinner {
    width: 50px;
    height: 50px;
    border: 3px solid #f3f3f3;
    border-top: 3px solid var(--primary-color);
    border-radius: 50%;
    animation: spin 1s linear infinite;
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

.data-chart-container {
    position: relative;
    height: 400px;
    margin-bottom: 20px;
}
</style>
{% endblock %}

{% block content %}
<div class="device-data">
    <div class="data-header">
        <h2>设备数据</h2>
        <div style="display: flex; gap: 15px; align-items: center;">
            <span class="status-indicator {{ 'status-online' if device.is_online else 'status-offline' }}"></span>
            {{ '在线' if device.is_online else '离线' }}
            <button class="btn btn-primary" onclick="refreshData()" title="刷新数据">
                <i class="fas fa-sync-alt"></i> 刷新
            </button>
            <button class="btn btn-secondary" onclick="exportData()">
                <i class="fas fa-download"></i> 导出数据
            </button>
        </div>
    </div>
    
    <div class="device-info">
        <div class="info-item">
            <span class="info-label">设备名称</span>
            <span class="info-value">{{ device.name }}</span>
        </div>
        <div class="info-item">
            <span class="info-label">设备类型</span>
            <span class="info-value">{{ device.device_type }}</span>
        </div>
        <div class="info-item">
            <span class="info-label">所属农田</span>
            <span class="info-value">{{ field.name if field else '未分配' }}</span>
        </div>
        <div class="info-item">
            <span class="info-label">创建时间</span>
            <span class="info-value">{{ device.created_at }}</span>
        </div>
    </div>
    
    <div class="data-filters">
        <div class="form-group">
            <label for="auto-refresh">
                <input type="checkbox" id="auto-refresh" onchange="toggleAutoRefresh()">
                <span>自动刷新（30秒）</span>
            </label>
        </div>
        <div class="form-group">
            <label for="time-range">时间范围</label>
            <select id="time-range" name="time-range" onchange="handleTimeRangeChange()">
                <option value="24h">最近24小时</option>
                <option value="7d">最近7天</option>
                <option value="30d">最近30天</option>
                <option value="custom">自定义</option>
            </select>
            <div id="custom-range" style="display: none; margin-top: 10px;">
                <label for="start-time">开始时间</label>
                <input type="datetime-local" id="start-time" name="start-time" onchange="updateData()">
                <span style="margin: 0 10px;">至</span>
                <label for="end-time">结束时间</label>
                <input type="datetime-local" id="end-time" name="end-time" onchange="updateData()">
            </div>
        </div>
        <div class="form-group">
            <label for="data-type">数据类型</label>
            <select id="data-type" name="data-type" onchange="updateData()">
                <option value="all">全部</option>
                {% if device.device_type == 'soil_moisture' %}
                <option value="moisture">土壤湿度</option>
                <option value="temperature">土壤温度</option>
                {% elif device.device_type == 'weather' %}
                <option value="temperature">气温</option>
                <option value="humidity">湿度</option>
                <option value="rainfall">降雨量</option>
                {% endif %}
            </select>
        </div>
    </div>
    
    <div class="data-chart-container">
        <div id="chart-loading" class="loading-overlay" style="display: none;">
            <div class="loading-spinner"></div>
        </div>
        <div class="data-chart" id="data-chart"></div>
    </div>
    
    <table class="data-table">
        <thead>
            <tr>
                <th>时间</th>
                <th>数据类型</th>
                <th>数值</th>
                <th>单位</th>
            </tr>
        </thead>
        <tbody id="data-table-body">
            <!-- 数据行将通过JavaScript动态添加 -->
        </tbody>
    </table>
</div>
{% endblock %}

{% block scripts %}
<script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
<script>
let chart;
const deviceId = {{ device.id }};
const initialData = {{ initial_data|tojson|safe }};
let refreshTimer = null;

// 初始化图表
function initChart() {
    if (!document.getElementById('data-chart')) {
        console.error('Chart container not found');
        return;
    }

    // 初始化ECharts实例
    chart = echarts.init(document.getElementById('data-chart'));
    
    // 处理初始数据
    const processedData = processChartData(initialData);
    
    // 设置图表配置
    const option = {
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross'
            }
        },
        legend: {
            data: processedData.legends
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: processedData.timestamps,
            axisLabel: {
                rotate: 45
            }
        },
        yAxis: [
            {
                type: 'value',
                name: '温度 (°C)',
                position: 'left',
                axisLine: {
                    show: true,
                    lineStyle: {
                        color: '#ff7300'
                    }
                },
                axisLabel: {
                    formatter: '{value} °C'
                }
            },
            {
                type: 'value',
                name: '湿度 (%)',
                position: 'right',
                axisLine: {
                    show: true,
                    lineStyle: {
                        color: '#5470c6'
                    }
                },
                axisLabel: {
                    formatter: '{value} %'
                }
            }
        ],
        series: processedData.series
    };
    
    chart.setOption(option);
    
    // 立即加载数据
    updateData();
}

// 刷新数据
function refreshData() {
    const button = document.querySelector('button[onclick="refreshData()"]');
    const icon = button.querySelector('i');
    
    // 添加旋转动画
    icon.style.animation = 'spin 1s linear infinite';
    
    updateData().finally(() => {
        // 停止旋转动画
        icon.style.animation = '';
    });
}

// 切换自动刷新
function toggleAutoRefresh() {
    const autoRefresh = document.getElementById('auto-refresh').checked;
    
    if (autoRefresh) {
        // 启动定时器，每30秒刷新一次
        refreshTimer = setInterval(refreshData, 30000);
    } else {
        // 清除定时器
        if (refreshTimer) {
            clearInterval(refreshTimer);
            refreshTimer = null;
        }
    }
}

// 页面卸载时清除定时器
window.addEventListener('unload', function() {
    if (refreshTimer) {
        clearInterval(refreshTimer);
    }
});

// 更新数据
async function updateData() {
    // 显示加载动画
    const loadingEl = document.getElementById('chart-loading');
    loadingEl.style.display = 'flex';
    
    // 禁用所有控件
    const controls = document.querySelectorAll('select, input, button');
    controls.forEach(control => control.disabled = true);
    
    const timeRange = document.getElementById('time-range').value;
    const dataType = document.getElementById('data-type').value;
    let queryParams = new URLSearchParams();
    
    console.log('Updating data...', { timeRange, dataType });  // 调试日志
    
    if (timeRange === 'custom') {
        const startTime = document.getElementById('start-time').value;
        const endTime = document.getElementById('end-time').value;
        if (!startTime || !endTime) {
            alert('请选择开始和结束时间');
            loadingEl.style.display = 'none';
            controls.forEach(control => control.disabled = false);
            return;
        }
        queryParams.set('start_time', startTime);
        queryParams.set('end_time', endTime);
    } else {
        queryParams.set('time_range', timeRange);
    }
    queryParams.set('data_type', dataType);
    
    const url = `/api/devices/${deviceId}/data?${queryParams.toString()}`;
    console.log('Fetching data from:', url);  // 调试日志
    
    try {
        const response = await fetch(url);
        if (!response.ok) {
            throw new Error('获取数据失败');
        }
        const data = await response.json();
        
        if (!data || !data.length) {
            showNoData();
            return;
        }
        
        updateChart(data);
        updateTable(data);
    } catch (error) {
        console.error('获取数据失败:', error);
        showError();
    } finally {
        // 隐藏加载动画
        loadingEl.style.display = 'none';
        // 启用所有控件
        controls.forEach(control => control.disabled = false);
    }
}

// 更新图表
function updateChart(data) {
    const processedData = processChartData(data);
    
    chart.setOption({
        xAxis: {
            data: processedData.timestamps
        },
        legend: {
            data: processedData.legends
        },
        series: processedData.series
    });
}

// 更新数据表格
function updateTable(data) {
    const tbody = document.getElementById('data-table-body');
    tbody.innerHTML = data.map(item => `
        <tr>
            <td>${new Date(item.timestamp).toLocaleString()}</td>
            <td>${getDataTypeName(item.data_type)}</td>
            <td>${item.value.toFixed(2)}${getUnit(item.data_type)}</td>
        </tr>
    `).join('');
}

// 显示无数据提示
function showNoData() {
    const tbody = document.getElementById('data-table-body');
    tbody.innerHTML = '<tr><td colspan="4" style="text-align: center;">暂无数据</td></tr>';
}

// 显示错误提示
function showError() {
    const option = {
        backgroundColor: '#fff',
        title: {
            text: '数据加载失败，请稍后重试',
            subtext: '点击刷新按钮重新加载',
            left: 'center',
            top: 'center',
            textStyle: {
                color: '#dc3545'
            },
            subtextStyle: {
                color: '#666'
            }
        }
    };
    chart.setOption(option);
    
    const tbody = document.getElementById('data-table-body');
    tbody.innerHTML = `
        <tr>
            <td colspan="4" style="text-align: center;">
                <div style="color: #dc3545; margin-bottom: 5px;">
                    <i class="fas fa-exclamation-circle"></i> 数据加载失败
                </div>
                <div style="color: #666; font-size: 0.9em;">
                    请检查网络连接后重试
                </div>
            </td>
        </tr>
    `;
}

// 获取数据类型名称
function getDataTypeName(type) {
    const types = {
        'moisture': '土壤湿度',
        'temperature': '温度',
        'humidity': '湿度',
        'rainfall': '降雨量'
    };
    return types[type] || type;
}

// 获取单位
function getUnit(type) {
    const units = {
        'moisture': '%',
        'temperature': '°C',
        'humidity': '%',
        'rainfall': 'mm'
    };
    return units[type] || '';
}

// 处理图表数据
function processChartData(data) {
    // 按数据类型分组
    const groupedData = {};
    const timestamps = [];
    const seen = new Set();
    
    data.forEach(item => {
        const time = new Date(item.timestamp).toLocaleString();
        if (!seen.has(time)) {
            timestamps.push(time);
            seen.add(time);
        }
        if (!groupedData[item.data_type]) {
            groupedData[item.data_type] = [];
        }
        groupedData[item.data_type].push(item.value);
    });
    
    // 生成图表系列
    const legends = [];
    const series = [];
    const colors = {
        temperature: '#ff7300',
        humidity: '#5470c6',
        moisture: '#91cc75',
        rainfall: '#73c0de'
    };
    
    Object.entries(groupedData).forEach(([type, values]) => {
        const name = getDataTypeName(type);
        legends.push(name);
        
        series.push({
            name: name,
            type: 'line',
            smooth: true,
            yAxisIndex: type === 'temperature' ? 0 : 1,
            data: values,
            itemStyle: {
                color: colors[type]
            },
            areaStyle: {
                opacity: 0.1
            }
        });
    });
    
    return {
        timestamps,
        legends,
        series
    };
}

// 页面加载完成后初始化图表
window.addEventListener('load', initChart);

// 窗口大小改变时调整图表大小
window.addEventListener('resize', function() {
    chart && chart.resize();
});

// 处理时间范围变化
function handleTimeRangeChange() {
    const timeRange = document.getElementById('time-range').value;
    const customRange = document.getElementById('custom-range');
    
    if (timeRange === 'custom') {
        customRange.style.display = 'block';
        // 设置默认时间范围（最近24小时）
        const end = new Date();
        const start = new Date(end - 24 * 60 * 60 * 1000);
        document.getElementById('end-time').value = end.toISOString().slice(0, 16);
        document.getElementById('start-time').value = start.toISOString().slice(0, 16);
    } else {
        customRange.style.display = 'none';
        updateData();
    }
}

// 导出数据
async function exportData() {
    const exportBtn = document.querySelector('button[onclick="exportData()"]');
    const originalText = exportBtn.innerHTML;
    
    // 获取数据范围描述
    const timeRange = document.getElementById('time-range').value;
    let timeDesc = '';
    if (timeRange === 'custom') {
        const startTime = new Date(document.getElementById('start-time').value).toLocaleString();
        const endTime = new Date(document.getElementById('end-time').value).toLocaleString();
        timeDesc = `${startTime} 至 ${endTime}`;
    } else {
        const ranges = {
            '24h': '最近24小时',
            '7d': '最近7天',
            '30d': '最近30天'
        };
        timeDesc = ranges[timeRange] || timeRange;
    }
    
    // 确认导出
    if (!confirm(`确定要导出以下数据吗？\n\n时间范围：${timeDesc}\n数据类型：${getDataTypeName(document.getElementById('data-type').value)}`)) {
        return;
    }
    
    try {
        exportBtn.disabled = true;
        exportBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 导出中...';
        
        const timeRange = document.getElementById('time-range').value;
        const dataType = document.getElementById('data-type').value;
        let queryParams = new URLSearchParams();
        
        if (timeRange === 'custom') {
            const startTime = document.getElementById('start-time').value;
            const endTime = document.getElementById('end-time').value;
            if (!startTime || !endTime) {
                alert('请选择开始和结束时间');
                return;
            }
            queryParams.set('start_time', startTime);
            queryParams.set('end_time', endTime);
        } else {
            queryParams.set('time_range', timeRange);
        }
        queryParams.set('data_type', dataType);
        
        window.location.href = `/api/devices/${deviceId}/data/export?${queryParams.toString()}`;
    } finally {
        // 延迟恢复按钮状态，给用户一个视觉反馈
        setTimeout(() => {
            exportBtn.disabled = false;
            exportBtn.innerHTML = originalText;
        }, 1000);
    }
}
</script>
{% endblock %} 